package com.ruoyi.web.controller.file;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.file.domain.SysFileResult;
import com.ruoyi.file.service.ISysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@Api(tags = "公共服务：文件上传接口")
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @ApiOperation(value = "获取文件服务器地址")
    @PostMapping("getMinioUrl")
    public AjaxResult getMinioUrl() {
        return AjaxResult.success("success",sysFileService.getMinioUrl());
    }

    /**
     * 文件上传请求
     */
    @ApiOperation(value = "文件上传请求")
    @PostMapping("upload")
    public R<SysFileResult> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFileResult sysFile = new SysFileResult();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("uploadGetPath")
    public R<SysFileResult> uploadGetPath(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFileResult sysFile = new SysFileResult();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}